package com.gzl.b2b.demo.common.aspect;

import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @version 1.0, 2019/4/22
 */
@Aspect
@Component
public class WatchMethodTimeAspect {
    private Logger log = LoggerFactory.getLogger(WatchMethodTimeAspect.class);

    /**
     * 因为路径配置不对，可能会一直导致无法进行拦截
     */
    @Pointcut("execution(* com.gzl.b2b.demo.service..*(..)) && @annotation(com.gzl.b2b.demo.common.annotation.WatchMethodTime)")
    public void aspect() {}


    @Around("aspect()")
    public Object aroundMethod(ProceedingJoinPoint pj) throws Exception{
        Object target = pj.getTarget();
        //类名
        Class<?> classz = target.getClass();
        //执行方法名
        String methodName = pj.getSignature().getName();
        Object result = null;

        // 创建一个计时器
        StopWatch watch = new StopWatch();


        try {
            // 计时器开始
            watch.start();

            result = pj.proceed();

            // 计时器停止
            watch.stop();
        }catch (Throwable e) {
            log.error(e.getMessage());
        }

        // 获取计时器计时时间
        Long time = watch.getTime();
        log.info("Execute：ClassName：[{}]，MethodName：[{}]，Execution time：[{}] ms", classz.getName(), methodName, time);
        return result;
    }
}
